const { db, genid } = require('../database/index')
const fs = require('fs')

const uploadHandler = {
  async upload(req, res) {
    if (!req.files) {
      return res.send({
        "errno": 1, // 只要不等于 0 就行
        "message": "失败"
      })
    }

    let files = req.files;
    const ret_files = [];

    for (const file of files) {
      // 获取文件名后缀
      let file_ext = file.originalname.substring(file.originalname.lastIndexOf('.') + 1);
      // 随机文件名
      let file_name = genid.NextId() + '.' + file_ext;

      // 文件的修改与移动
      fs.renameSync(
        process.cwd() + '/public/upload/temp/' + file.filename,
        process.cwd() + '/public/upload/' + file_name,
      )
      ret_files.push('/upload/' + file_name);
    }
    res.send({
      "errno": 0, // 注意：值是数字，不能是字符串
      "data": {
        "url": ret_files[0], // 图片 src ，必须
      }
    })
  }
}

module.exports = uploadHandler;